<script setup lang="ts">
import dayjs from 'dayjs'
import { useUserInfoStore } from '@/store/userInfo'
import { submitPaymentAPI } from '@/apis/submitPayment'
import { uploadImageAPI } from '@/apis/uploadImage'

// Assets
import modalSuccessIcon from '@/static/images/modal/success.png'

const router = useRouter()
const userInfoStore = useUserInfoStore()

const projectId = ref('')

// 表单数据
const formData = ref({
  pay_node: '' as '1' | '2' | '3',
  pay_images: [] as string[], // 打款照片
  pay_time: '', // 打款时间
  pay_money: '', // 打款金额
  pay_desc: '', // 打款说明
})

// 表单校验规则
const rules = {
  pay_images: [
    {
      required: true,
      transform(value: string[]) {
        return value.join(',')
      },
      message: '打款照片不可为空',
      trigger: ['blur', 'change'],
    },
  ],
  pay_time: [
    { required: true, message: '打款时间不可为空', trigger: ['blur', 'change'] },
  ],
  pay_money: [
    { required: true, message: '打款金额不可为空', trigger: ['blur', 'change'] },
  ],
  pay_desc: [
    { required: true, message: '打款备注不可为空', trigger: ['blur', 'change'] },
  ],
}

// 表单组件 ref
const formRef = ref<any>(null)
// loading 状态
const loading = ref(false)
// 是否显示表单提交成功弹窗
const isShowSuccessModal = ref(false)

/* ------------------------------ 选择打款节点 START ------------------------------ */
const displayedPaymentNode = computed(() => {
  if (formData.value.pay_node === '1')
    return '首期款'
  else if (formData.value.pay_node === '2')
    return '中期款'
  else if (formData.value.pay_node === '3')
    return '尾款'
})

function handleSelectPaymentNode() {
  uni.showActionSheet({
    itemList: ['首期款', '中期款', '尾款'],
    success: (result) => {
      if (result.tapIndex === 0)
        formData.value.pay_node = '1'
      else if (result.tapIndex === 1)
        formData.value.pay_node = '2'
      else if (result.tapIndex === 2)
        formData.value.pay_node = '3'
    },
  })
}
/* ------------------------------- 选择打款节点 END ------------------------------- */

/* ------------------------------ 选择打款照片 START ------------------------------ */
/**
 * @description 处理选择打款照片事件
 */
function handlePickPaymentImage() {
  uni.showActionSheet({
    itemList: ['拍摄', '从手机相册中选择'],
    success: (result) => {
      const sourceType = result.tapIndex === 0 ? 'camera' : 'album'
      uni.chooseMedia({
        count: 9,
        mediaType: ['image'],
        sourceType: [sourceType],
        sizeType: ['compressed'],
        success: (result) => {
          if (result.tempFiles.length > 0) {
            // 遍历照片临时路径的数组，将照片上传至服务器，将返回的 url 存入 formData
            result.tempFiles.forEach(async (path) => {
              const res = await uploadImageAPI(path.tempFilePath, userInfoStore.userInfo!.token!)
              if (res.data) {
                const resData = JSON.parse(res.data)
                if (resData.code === 1)
                  formData.value.pay_images.push(resData.data.fullurl)
                else
                  uni.showToast({ title: resData.msg, icon: 'none' })
              }
              else {
                uni.showToast({ title: '上传图片失败', icon: 'none' })
              }
            })
          }
          else {
            uni.showToast({ title: '没有获取到照片', icon: 'none' })
          }
        },
      })
    },
  })
}

/**
 * @description 处理删除打款照片事件
 */
function handleDeletePaymentImage(picture: string) {
  formData.value.pay_images = formData.value.pay_images
    .filter(item => item !== picture)
}
/* ------------------------------- 选择打款照片 END ------------------------------- */

/* ------------------------------ 选择打款时间 START ------------------------------ */
// 日历组件 ref
const paymentTimeCalendarsRef = ref<any>(null)
// 时间选择器状态
const timePickerSelection = ref<number[]>([])

// 初始化时间选择器默认 state
onMounted(() => {
  const now = dayjs(Date.now())
  timePickerSelection.value[0] = now.hour()
  timePickerSelection.value[1] = now.minute()
})

// 临时选择的包含日期和时间的数组，[0] -> date，[1] -> time
const tempDateStringList = ref<string[]>([])

// 显示在 cell 中的 date
const displayedPaymentDate = computed(() => {
  if (tempDateStringList.value[0])
    return dayjs(tempDateStringList.value[0]).format('YYYY/MM/DD')
})

// 显示在 cell 中的 time
const displayedPaymentTime = computed(() => {
  return tempDateStringList.value[1]
})

/**
 * @description 处理日期选择器确定事件
 */
function handleChoosePaymentDate(e: any) {
  tempDateStringList.value[0] = e.fulldate
  updatePaymentTime()
}

/**
 * @description 处理时间选择器确定事件
 */
function handleChoosePaymentTime(e: any) {
  tempDateStringList.value[1] = e.detail.value
  updatePaymentTime()
}

/**
 * @description 将选择的时间同步到 formData
 */
function updatePaymentTime() {
  if (tempDateStringList.value.length === 2) {
    const dateInstance = dayjs(`${tempDateStringList.value[0]} ${tempDateStringList.value[1]}`, 'YYYY-MM-DD HH:mm')
    formData.value.pay_time = `${dateInstance.unix()}`
  }
}
/* ------------------------------- 选择打款时间 END ------------------------------- */

onLoad(async (options) => {
  if (options && options.project_id)
    projectId.value = options.project_id
})

/**
 * @description 处理提交表单事件
 */
const handleSubmit = useThrottleFn(() => {
  // 确保 token 存在
  if (userInfoStore.userInfo && userInfoStore.userInfo.token) {
    // 校验表单
    formRef.value.validate()
      .then(async () => {
        // 表单校验通过

        // 控制加载状态
        loading.value = true

        // 提交表单
        try {
          const res = await submitPaymentAPI({
            ...formData.value,
            pay_images: formData.value.pay_images.join(','),
            project_id: projectId.value,
          }, userInfoStore.userInfo!.token!)
          loading.value = false
          if (res.data?.code === 1)
            // 提交成功
            isShowSuccessModal.value = true
          else
            // 服务器返回错误
            uni.showToast({ title: res.data?.msg, icon: 'none' })
        }
        catch (error) {
          // 请求发生错误
          loading.value = false
          uni.showToast({ title: '上传失败，请重试', icon: 'none' })
        }
      })
      .catch((errors: AnyObject[]) => {
        // 表单验证失败
        if (errors.length > 0)
          uni.showToast({ title: errors[0].message, icon: 'none' })
      })
  }
  else {
    uni.showToast({ title: '录入失败，请重新打开页面', icon: 'none' })
  }
}, 1000)

function handleExit() {
  router.back()
}
</script>

<template>
  <view class="min-h-screen bg-#F8F8F8">
    <Spacer height="30" />
    <uv-form ref="formRef" :model="formData" :rules="rules">
      <view class="mx-30rpx bg-white rounded-10rpx">
        <uv-form-item prop="pay_images" :custom-style="{ padding: 0 }">
          <ListCell label="打款节点" @tap="handleSelectPaymentNode">
            <ListLink :value="displayedPaymentNode" placeholder="请选择打款节点" />
          </ListCell>
        </uv-form-item>
        <Divider />
        <uv-form-item prop="pay_images" :custom-style="{ padding: 0 }">
          <ListCell direction="column" label="打款信息">
            <PictureGrid
              :pictures="formData.pay_images" mode="edit" :width="630"
              :cols="4" @pick-image="handlePickPaymentImage" @delete="handleDeletePaymentImage"
            />
          </ListCell>
        </uv-form-item>
        <Divider />
        <uv-form-item prop="pay_time" :custom-style="{ padding: 0 }">
          <ListCell label="打款日期" @tap="paymentTimeCalendarsRef.open()">
            <ListLink :value="displayedPaymentDate" placeholder="请选择打款日期" />
          </ListCell>
        </uv-form-item>
        <Divider />
        <uv-form-item prop="pay_time" :custom-style="{ padding: 0 }">
          <picker :value="timePickerSelection" mode="time" @change="handleChoosePaymentTime">
            <ListCell label="打款时间">
              <ListLink :value="displayedPaymentTime" placeholder="请选择打款时间" />
            </ListCell>
          </picker>
        </uv-form-item>
        <Divider />
        <uv-form-item prop="pay_money" :custom-style="{ padding: 0 }">
          <ListCell label="打款金额">
            <ListInput v-model="formData.pay_money" type="number" placeholder="请输入打款金额" />
          </ListCell>
        </uv-form-item>
        <Divider />
        <uv-form-item prop="pay_desc" :custom-style="{ padding: 0 }">
          <ListCell direction="column" label="打款备注">
            <textarea
              v-model="formData.pay_desc"
              class="box-border w-full min-h-200rpx p-30rpx text-28rpx text-#333333 bg-#F0F0F0 rounded-10rpx"
              placeholder-style="color: #999999"
              :maxlength="-1"
              placeholder="请输入打款备注"
            />
          </ListCell>
        </uv-form-item>
      </view>
      <Spacer height="138" />
      <RGButton
        class="z-10 fixed bottom-80rpx x-center"
        @tap="handleSubmit"
      >
        提交审核
      </RGButton>
      <Spacer height="100" />
    </uv-form>
    <uv-calendars
      ref="paymentTimeCalendarsRef"
      :insert="false"
      round="20rpx"
      confirm-color="#FF6D0A"
      @confirm="handleChoosePaymentDate"
    />
    <uv-overlay :show="isShowSuccessModal" @tap="handleExit">
      <uv-transition mode="zoom-in" :show="isShowSuccessModal">
        <view class="relative w-screen h-screen">
          <JZTModal
            :icon="modalSuccessIcon"
            title="打款信息提交成功"
            content=""
            button-label="确定"
            @confirm="handleExit"
          />
        </view>
      </uv-transition>
    </uv-overlay>
  </view>
</template>

<route lang="yaml">
name: 'uploadPayment'
style:
  navigationBarTitleText: '上传打款信息'
layout: 'custom'
</route>
